<?php

namespace app\api\controller;

use app\api\model\Order;
use app\api\model\PlatformLog;
use app\api\model\SaveIng;
use app\api\model\UserBill;
use app\common\controller\Api;
use EasyWeChat\Factory;
use fast\Random;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use think\facade\Log;
use think\Model;
use think\Request;

/**
 * 回调接口.
 */
class Notify
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    protected $model;
    protected $platform_model;
    /**
     * 构造方法
     * @access public
     * @param Request $request Request 对象
     */
    public function __construct(Request $request = null)
    {
        $this->model = new Order();
        $this->platform_model = new PlatformLog();
    }

    /**
     * 预约下单回调.
     */
    public function orderNotify()
    {
        Log::write('预约下单支付回调逻辑开始'.date('Y-m-d H:i:s',time()));
        $config= Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            Log::write($message);
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = $this->model->where('out_trade_no', $out_trade_no)->find();
                //如果该订单未找到或已支付,返回true
                if (!$order) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status'=> 2,
                    'transaction_id'=>$message['transaction_id'], //微信支付订单号
                    'time_end'=>strtotime($message['time_end']), //支付完成时间
                    'total_fee'=>$message['total_fee'] / 100, //支付金额
                ];
                $res = $this->model->where('out_trade_no', $out_trade_no)->update($upda_data);
                //平台流水
                $platform_log = $this->platform_model->where(['user_id' => $order['user_id'], 'type' => 1, 'order_id' => $order['id']])->find();
                if(!$platform_log){
                    $this->platform_model->save(['user_id' => $order['user_id'], 'amount' => $order['all_money'], 'type' => 1, 'log_note' => '预约下单支付', 'createtime' => time(), 'order_id' => $order['id']]);
                }
                Log::write('预约下单支付回调逻辑结束'.date('Y-m-d H:i:s',time()));
                return true;
            }
        });
        return $response->send();
    }


    /**
     * 预约下单回调.
     */
    public function rechargeSavingNotify()
    {

        $config = Config::get('config_wechat.wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) use ($app) {
            if ($message['return_code'] == "SUCCESS" && $message["result_code"] == "SUCCESS") {
                $out_trade_no = $message['out_trade_no'];//订单号
                $order = Db::name('saving_order')->where(['out_trade_no' => $out_trade_no, 'status' => 0])->find();
                //如果该订单未找到或已支付,返回true
                if (!$order) {
                    return true;
                }
                //更改订单状态
                $upda_data = [
                    'status' => 2,
                    'transaction_id' => $message['transaction_id'], //微信支付订单号
                    'pay_time' => time(), //支付完成时间
                    'pay_money' => $message['total_fee'] / 100, //支付金额
                ];
                try {
                    $user = Db::name('user')->where(['id' => $order['user_id']])->find();
                    Db::startTrans();
                    Db::name('saving_order')->where('out_trade_no', $out_trade_no)->update($upda_data);
                    //获取储蓄卡信息
                    $savingItem = (new SaveIng())->where(['id' => $order['saving_id']])->find();
                    if($savingItem['type'] == 1){
                        //篮球卡
                        $basketballDiscount = $savingItem['discount'];
                        $update['basketball_discount'] = $basketballDiscount;
                    }else{
                        $badmintonDiscount = $savingItem['discount'];
                        $update['badminton_discount'] = $badmintonDiscount;
                    }

                    //执行增加金额
                    $amount = $order['pay_money'] + $user['wallet'];
                    $update['wallet'] = $amount;
                    $update['updatetime'] = time();
                    Db::name('user')->where(['id' => $order['user_id']])->update($update);
                    //添加记录
                    $userBill['user_id'] = $order['user_id'];
                    $userBill['title'] = $savingItem['type'] == 1?"篮球卡充值":"羽毛球卡充值";
                    $userBill['type'] = 1;
                    $userBill['amount'] = $order['pay_money'];
                    (new UserBill())->addUserBill($userBill);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    Log::write('预约下单支付回调逻辑结束' . $e->getMessage());
                }
                return true;
            }
        });
        return $response->send();
    }

}
